package br.com.ds3.interceptor;

import java.io.Serializable;
import java.lang.reflect.Field;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import br.com.ds3.annotation.CharCase;

@SuppressWarnings("serial")
public class HibernateUpperCaseInterceptor extends EmptyInterceptor {
	public boolean onSave(Object entity, Serializable id, Object[] currentState, String[] propertyNames, Type[] types) {
		convertProperties(entity, currentState, propertyNames, types);
			
		return super.onSave(entity, id, currentState, propertyNames, types);
	}
	
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,	Object[] previousState, String[] propertyNames,	Type[] types) {	
		convertProperties(entity, currentState, propertyNames, types);
		
		return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
	}
	
	private void convertProperties(Object entity, Object[] currentState, String[] propertyNames, Type[] types) {

		for (int i = 0; i < currentState.length; i++) {
			if (currentState[i] instanceof String && currentState[i] != null) {
				Field field = null;
				
				try {
					field = entity.getClass().getDeclaredField(propertyNames[i]);
				} catch (NoSuchFieldException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				}
				
				if (field.isAnnotationPresent(CharCase.class)) {
					switch (field.getAnnotation(CharCase.class).caseOption()) {
					case LOWER:
						currentState[i] = ((String) currentState[i]).toLowerCase();
						break;
					case UPPER:
						currentState[i] = ((String) currentState[i]).toUpperCase();
						break;
					default:
						currentState[i] = ((String) currentState[i]).toUpperCase();
						break;
					}
				} else {
					currentState[i] = ((String) currentState[i]).toUpperCase();
				}
			}
		}
	}
}
